package com.weijianhuawen.wjblog.jwt.service;

import com.weijianhuawen.wjblog.common.domain.dos.UserDo;
import com.weijianhuawen.wjblog.common.domain.dos.UserRoleDo;
import com.weijianhuawen.wjblog.common.domain.mapper.UserMapper;
import com.weijianhuawen.wjblog.common.domain.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version: java version 8
 * @Author: weijianhuawen
 * @description:
 * @date: 2024-10-16 0:35
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //数据库查询用户
        UserDo userDo = userMapper.findByUsername(username);

        if (Objects.isNull(userDo)) {
            //用户不存在，没有注册
            throw new UsernameNotFoundException("用户不存在，请注册");
        }

        //用户角色
        List<UserRoleDo> roleDos = userRoleMapper.selectUserRoleByUsername(username);
        String[] roleArr = null;
        //转换为数组
        if (!CollectionUtils.isEmpty(roleDos)) {
            List<String> roles = roleDos.stream().map(p -> p.getRole()).collect(Collectors.toList());
            roleArr = roles.toArray(new String[roles.size()]);
        }

        return User.withUsername(userDo.getUsername())
                .password(userDo.getPassword())
                .authorities(roleArr)
                .build();
    }
}
